package com.zjitc.service.imp;/**
 * Create by IntelliJ IDEA
 *
 * @author: MaoYongQi
 * @date-Time: 2018/4/2 11:28
 * @description:
 */

import com.github.pagehelper.PageHelper;
import com.zjitc.common.ServerResponse;
import com.zjitc.dao.ShippingDao;
import com.zjitc.model.Shipping;
import com.zjitc.service.ShippingService;
import java.util.List;
import javax.servlet.http.HttpSession;

import com.zjitc.utils.Conster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Create by IntelliJ IDEA
 *
 * @author: MaoYongQi
 * @date-Time: 2018/4/2 11:28
 * @description:
 */
@Service
public class ShippingServiceImpl implements ShippingService {

  @Autowired
  private ShippingDao dao;

  @Override
  public ServerResponse<Shipping> add(Shipping shipping) {
    Date date = new Date();
    try {
      List<Shipping> shippingList = dao.findAll();
      for (Shipping sp : shippingList) {
        sp.setUpdateTime(null);
        sp.setCreateTime(null);
        sp.setId(null);
        if (sp.equals(shipping)) {
          return ServerResponse.createError("新建地址失败");
        }
      }
      dao.add(shipping);
      int maxid = dao.findMAXID();
      Shipping s = new Shipping(maxid);
      return ServerResponse.createSuccess(s, "新建地址成功");
    } catch (Exception e) {
      e.printStackTrace();
      return ServerResponse.createError("新建地址失败");
    }
  }

  @Override
  public ServerResponse<Shipping> del(String shippingId) {
    try {
      int del = dao.del(shippingId);
      if (del == 0){
        return ServerResponse.createSuccess("地址并不存在");
      }
      return ServerResponse.createSuccess("删除地址成功");
    } catch (Exception e) {
      return ServerResponse.createError("删除地址失败");
    }
  }

  @Override
  public ServerResponse<Shipping> update(Shipping shipping) {
    try {
      shipping.setUpdateTime(new Date());
      dao.update(shipping);
      return ServerResponse.createSuccess("更新地址成功");
    } catch (Exception e) {

      return ServerResponse.createError("更新地址失败");
    }
  }

  @Override
  public ServerResponse<Shipping> select(String shippindId, HttpSession session) {
    Object user = session.getAttribute(Conster.USER);
    if (user == null) {
      return ServerResponse.createError("请登录后查询");
    }
    Shipping shipping = dao.select(shippindId);
    return ServerResponse.createSuccess(shipping);
  }

  @Override
  public ServerResponse<Shipping> selectList(Integer pageNum, Integer pageSize,
      HttpSession session) {
    Object user = session.getAttribute(Conster.USER);
    if (user == null) {
      return ServerResponse.createError("请登录后查询");
    }
    PageHelper.startPage(pageNum, pageSize);
    try{
    List<Shipping> shippingList = dao.selectAllShipping();
    return ServerResponse.createSuccess(shippingList);
    }catch (Exception e){
      e.printStackTrace();
      return ServerResponse.createError("出错了");
    }
  }
}
